package com.jzr.medical.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jzr.common.entity.vo.Result;
import com.jzr.common.entity.vo.ResultPage;
import com.jzr.common.util.FileUtil;
import com.jzr.common.util.U;
import com.jzr.common.util.UrlUtil;
import com.jzr.medical.common.SecurityHelper;
import com.jzr.medical.db1.dto.FoodMenuDto;
import com.jzr.medical.db1.model.TFoodMenu;
import com.jzr.medical.db1.service.FoodMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/foodMenu")
public class FoodMenuController {
    @Value("${file.foodPic-upload-folder}")
    private String uploadFolder;

    @Value("${file.foodPic-download-url}")
    private String downloadUrl;

    @Autowired
    private FoodMenuService foodMenuService;

    private TFoodMenu insertOrUpdate(TFoodMenu record){
        if(record == null){return null;}
        record.setUpdateBy(SecurityHelper.getUserId());
        record.setUpdateTime(LocalDateTime.now());
        boolean isOk = record.getId() == null ? foodMenuService.save(record) : foodMenuService.updateById(record);
        if(isOk) {
            return foodMenuService.getById(record.getId());
        }
        return null;
    }

    @PostMapping("/list")
    public ResultPage<TFoodMenu> list(@RequestBody FoodMenuDto record){
        QueryWrapper<TFoodMenu> qw = new QueryWrapper<>();
        qw.eq(U.isNotBlank(record.getType()),TFoodMenu.Type_,record.getType())
                .likeRight(U.isNotBlank(record.getName()),TFoodMenu.Name_,record.getName());
        IPage<TFoodMenu> page = foodMenuService.page(new Page<>(record.getPageNum(),record.getPageSize()),qw);

        List<TFoodMenu> list = page.getRecords();
        if(list != null){
            for(TFoodMenu m : list){
                if(U.isNotBlank(m.getImgUrl())) {
                    m.setImgUrl(UrlUtil.concat(downloadUrl, m.getImgUrl()));
                }
            }
        }
        return ResultPage.success(page);
    }

    @PostMapping("/save")
    public Result<TFoodMenu> save(TFoodMenu record){
        if(record == null){
            return null;
        }
        //不直接更新imgUrl;
        record.setImgUrl(null);

        if(U.isBlank(record.getName())){
            return Result.fail("请输入名称");
        }
        if(U.isBlank(record.getPrice())){
            return Result.fail("请输入价格");
        }
        if(U.isBlank(record.getIntroduce())){
            return Result.fail("请输入简介");
        }
        if(record.getId() == null) {
            Integer oldId = foodMenuService.getId(new QueryWrapper<TFoodMenu>().eq(TFoodMenu.Name_,record.getName()));
            if (oldId != null) {
                return Result.fail("\"" + record.getName() + "\"已经存在了,不能重复添加");
            }
        }
        TFoodMenu ret = insertOrUpdate(record);
        if(ret != null) {
            if (U.isNotBlank(ret.getImgUrl())) {
                ret.setImgUrl(UrlUtil.concat(downloadUrl, ret.getImgUrl()));
            }
            return Result.success(ret);
        }
        return Result.fail("保存失败");
    }

    @PostMapping("/delete")
    public Result<Boolean> delete(Integer id){
        Boolean ret = foodMenuService.removeById(id);
        return Result.success("成功",ret);
    }

    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file, Integer id)  {
        if (file.isEmpty()) {
            return Result.fail("上传失败，请选择文件");
        }
        if(U.isBlank(id)){
            return Result.fail("记录不存在");
        }

        //用id做为文件名
        String fileName = id.toString() + "." + FileUtil.getExtension(file.getOriginalFilename());

        if(U.isBlank(uploadFolder)){
            return Result.fail("获取不了上传文件夹");
        }
        try {
            File fullPath = new File(uploadFolder);
            if (!fullPath.exists()) {
                return Result.fail("上传文件夹不存在," + fullPath.getAbsolutePath());
            }

            File dest = new File(fullPath, fileName);
            if(dest.exists()){
                dest.delete();
            }
            file.transferTo(dest);
        }catch (IOException e){
            e.printStackTrace();
            return Result.fail("保存文件失败");
        }

        try {
            TFoodMenu foodMenu = new TFoodMenu();
            foodMenu.setId(id);
            foodMenu.setImgUrl(fileName);
            foodMenu.setUpdateBy(SecurityHelper.getUserId());
            foodMenu.setUpdateTime(LocalDateTime.now());
            foodMenuService.updateById(foodMenu);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("保存记录失败");
        }

        String accessUrl = UrlUtil.concat(downloadUrl,fileName);
        return Result.success("保存成功",accessUrl);
    }

    @PostMapping("/update")
    public Result<TFoodMenu> update(TFoodMenu record){
        if(record == null){
            return Result.fail("数据不能为空");
        }
        if(U.isBlank(record.getId())){
            return Result.fail("记录不存在,无法更新");
        }
        TFoodMenu ret = insertOrUpdate(record);
        if (ret != null && U.isNotBlank(ret.getImgUrl())) {
            ret.setImgUrl(UrlUtil.concat(downloadUrl, ret.getImgUrl()));
            return Result.success(ret);
        }
        return Result.fail("保存失败");
    }

}
